#include "include/stock.hpp"
#include <QRandomGenerator>

Stock::Stock(const QString &code, const QString &name, double price)
    : code(code), name(name), price(price), change(0.0) {
  // 初始化历史记录
  QDateTime currentTime = QDateTime::currentDateTime();
  priceHistory.append(price);
  timeHistory.append(currentTime);
}

void Stock::updatePrice() {
  // 使用随机值模拟股价波动，波动范围在 -2% 到 2% 之间
  static std::random_device rd;
  static std::mt19937 gen(rd());
  static std::uniform_real_distribution<> dis(-2.0, 2.0);

  double changePercent = dis(gen);
  double oldPrice = price;
  price = price * (1 + changePercent / 100.0);

  // 保证价格不会为负
  if (price < 0.01) {
    price = 0.01;
  }

  // 更新涨跌幅
  change = ((price - oldPrice) / oldPrice) * 100.0;

  // 添加到历史记录
  priceHistory.append(price);
  timeHistory.append(QDateTime::currentDateTime());

  // 清理过时的历史数据
  cleanHistory();
}

const QVector<double> &Stock::getPriceHistory() const { return priceHistory; }

const QVector<QDateTime> &Stock::getTimeHistory() const { return timeHistory; }

void Stock::cleanHistory(int maxRecords) {
  // 如果历史记录超过最大值，则移除旧数据
  while (priceHistory.size() > maxRecords) {
    priceHistory.removeFirst();
    timeHistory.removeFirst();
  }
}
